package com.infomanage.service.syscfg;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import com.infomanage.authority.AuthorityBean;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.MessageDAO;
import com.infomanage.dao.MessageStateDAO;
import com.infomanage.enums.RoleType;
import com.infomanage.po.Message;
import com.infomanage.po.MessageState;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.StringUtil;
import com.infomanage.util.TimeUtil;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;

public class MessageService {

	public static Message loadMessage(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId = request.getParameter("itemId");
			MessageDAO dao = new MessageDAO();
			if (StringUtils.isEmpty(itemId))
				return null;
			return dao.find(Integer.parseInt(itemId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<Message> loadMessageList(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			MessageDAO dao = new MessageDAO();
			List<Message> list = dao.findAll();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void testFindNewMessage(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
			if(user == null)//未登录控制
				return;
			MessageDAO dao = new MessageDAO();
			Message msg = dao.findByState();
			if (msg != null) {
				String title = msg.getTitle();
				String content = msg.getContent();
				if(content != null && content.length() > 100){
					content = content.substring(0, 100);
				    content = content + "...";
				}
				StringBuffer msgDIV = new StringBuffer();
				msgDIV.append("<div class='top'>");
				msgDIV.append("      <div class='title'>系统通知</div>");
				msgDIV.append("		<span title='关闭' id='msgclose' onclick='closeDiv();'></span>");
				msgDIV.append("</div>");
				msgDIV.append(" <div class='center'>");
				msgDIV.append("		<h3>" + title + "</h3>");
				msgDIV.append("<p>" + content + "</p>");
				msgDIV.append("	</div>");
				msgDIV.append("	<div class='bottom'><a href='javascript:showDetail("+msg.getMessageId()+")' >查看</a>");
				msgDIV.append("	</div>");
				out.print(msgDIV.toString());
				if (SetMsgStateThread.flag == false) {
					SetMsgStateThread setMsgStateThread=new SetMsgStateThread(msg);
					setMsgStateThread.start();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static ReturnObject saveMessage(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			Message bean = new Message();
			bean.setContent(request.getParameter("content"));
			bean.setTimestamp(TimeUtil.showCurrentTime());
			bean.setTitle(request.getParameter("title"));
			bean.setState(1);
			MessageDAO dao = new MessageDAO();
			dao.add(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static ReturnObject removeMessage(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String studyId = request.getParameter("itemId");
			MessageDAO dao = new MessageDAO();
			dao.remove(Message.class, Integer.parseInt(studyId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static ReturnObject removeBatchMessage(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			MessageDAO dao = new MessageDAO();
			if (batchIds != null) {
				String[] ids = batchIds.split(";");
				for (String id : ids) {
					dao.remove(Message.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}

	public static List<Message> search(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			MessageDAO dao = new MessageDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			// 设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if (currPageNum == null) {
				page.setCurrentPageNum(1);
			} else {
				page.setCurrentPageNum(Integer.parseInt(currPageNum));

			}
			searchBean.setPage(page);
			List<Message> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int getPageCount(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			MessageDAO dao = new MessageDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1) / PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}

	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String deptName = request.getParameter("deptName");
		String personName = request.getParameter("personName");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(deptName)) {
			FieldBean field = new FieldBean("deptName", deptName);
			field.setLike(true);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(personName)) {
			FieldBean field = new FieldBean("personName", personName);
			field.setLike(true);
			searchBean.add(field);
		}

		// 设置权限
		User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
		if (user != null) {
			AuthorityBean authority = new AuthorityBean();
			authority.setRole(RoleType.valueOf(user.getRoleId()));
			authority.setDeptId(user.getAssociatedDept());
			searchBean.setAuthority(authority);
		}
		return searchBean;
	}
}
